package com.ly.security;

import com.ly.bean.Admin;
import com.ly.bean.Roles;
import com.ly.controller.RoleController;
import com.ly.service.AdminService;
import com.ly.service.MenuService;
import com.ly.service.RolesService;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 李岩
 * @date 2021/12/29-12:06
 * @describe
 */
@Component("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    private final Logger logger= LoggerFactory.getLogger(UserDetailsService.class);

    @Reference(url = "dubbo://localhost:20886")
    private RolesService rolesService;
    @Reference(url = "dubbo://localhost:20886")
    private AdminService adminService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        try {
            logger.info("当前登录的用户名  "+s);
            if (s=="" || "".equals(s))
                return null;
            //从数据库获取登录对象
            Admin loginAdmin = adminService.selectAdminByaName(s);
            System.out.println("loginAdmin  "+loginAdmin);
            if (loginAdmin==null)
                return null;
            List<Roles> rolesList = rolesService.selectRoleByaId(loginAdmin.getAId());
            List<GrantedAuthority> granList = new ArrayList<>();
            granList.add(new SimpleGrantedAuthority("ROLE_LOGIN"));
            for (Roles roles : rolesList) {
                granList.add(new SimpleGrantedAuthority(roles.getDescription()));
            }
            return new User(loginAdmin.getAName(),loginAdmin.getAPass(),granList);
        } catch (Exception e) {
            throw new UsernameNotFoundException("认证用户出现 异常"+e);
        }

    }
}
